"use client";

import { useState, useEffect, useCallback } from 'react';

export function useSessionState() {
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);

  // Read from localStorage on initialization
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const storedSessionId = localStorage.getItem('activeSessionId');
      if (storedSessionId) {
        setActiveSessionId(storedSessionId);
      }
    }
  }, []);

  // Listen for localStorage changes (cross-tab sync)
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'activeSessionId') {
        setActiveSessionId(e.newValue);
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  // Listen for custom events (same-tab sync)
  useEffect(() => {
    const handleSessionChange = (e: CustomEvent) => {
      const { sessionId } = e.detail;
      setActiveSessionId(sessionId);
    };

    window.addEventListener('sessionChanged', handleSessionChange as EventListener);
    return () => window.removeEventListener('sessionChanged', handleSessionChange as EventListener);
  }, []);

  // Switch to new session
  const switchToSession = useCallback(async (sessionId: string) => {
    try {
      // Check if already current session
      if (activeSessionId === sessionId) {
        return;
      }
      
      // Update state
      setActiveSessionId(sessionId);
      
      // Update localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('activeSessionId', sessionId);
      }
      
      // Trigger custom event
      window.dispatchEvent(new CustomEvent('sessionChanged', {
        detail: { sessionId }
      }));
    } catch (error) {
      throw error;
    }
  }, [activeSessionId]);

  // Clear session
  const clearSession = useCallback(() => {
    setActiveSessionId(null);
    
    if (typeof window !== 'undefined') {
      localStorage.removeItem('activeSessionId');
      
      window.dispatchEvent(new CustomEvent('sessionChanged', {
        detail: { sessionId: null }
      }));
    }
  }, []);

  // Check if current session matches
  const isCurrentSession = useCallback((sessionId: string) => {
    return activeSessionId === sessionId;
  }, [activeSessionId]);

  return {
    activeSessionId,
    switchToSession,
    clearSession,
    isCurrentSession,
  };
}